package com.echo.im.engin.pipeline;

import com.echo.im.common.dto.MessageDTO;
import com.echo.im.common.enums.MessageStatus;
import com.echo.im.engin.packet.in.PrivateMessageInPacket;
import com.echo.im.common.vo.PrivateMessageVO;
import com.echo.im.domain.friend.manager.FriendManager;
import com.echo.im.infrastructure.mq.event.model.store.PrivateStoreMessageEvent;
import com.echo.im.infrastructure.session.UserSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author: echo
 * @time: 2024-08-23
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PrivateMessageProcessPipeline extends AbstractMessageProcessPipeline<PrivateMessageInPacket,PrivateMessageVO> {

    private final PrivateStoreMessageEvent privateStoreMessageEvent;
    private final FriendManager friendManager;
    @Override
    protected void validateUser(UserSession session, MessageDTO<PrivateMessageInPacket> dto) {
        //校验用户信息
        PrivateMessageInPacket packet= dto.getPacket();
        if (!dto.getIsAnonymous()){
            friendManager.checkFriend(session.getUserId(), packet.getRecvId());
        }
    }

    @Override
    protected PrivateMessageVO createMessageVO(UserSession session,MessageDTO<PrivateMessageInPacket> dto) {
        //privateMessageVO在这个时候就已经定死了，后期不会再更改了
        PrivateMessageVO privateMessageVO = new PrivateMessageVO();

        if (dto.getIsNeedACK()){
            privateMessageVO.setSeqId(dto.getPacket().getSeqId());
        }

        privateMessageVO.setSendId(session.getUserId());
        privateMessageVO.setRecvId(dto.getPacket().getRecvId());
        privateMessageVO.setType(dto.getPacket().getType());
        privateMessageVO.setContent(dto.getPacket().getContent());
        privateMessageVO.setSendTime(new Date());
        privateMessageVO.setStatus(MessageStatus.NORMAL.code());

        return privateMessageVO;
    }

    @Override
    protected List<Long> getRecvIds(PrivateMessageVO messageVO) {
        return Collections.singletonList(messageVO.getRecvId());
    }

    @Override
    protected void persistMessage(PrivateMessageVO messageVO) {
        eventPublisher.publish(privateStoreMessageEvent, messageVO);
    }

}
